import * as Vue from 'vue'
import App from './App.vue'
import Router from './router/index.js'
import Store from './store/index.js'
import i18n from './locales'
import 'virtual:svg-icons-register'
import Dbant from "./dbant.js"
import config from "./config"
import api from './api'
import http from "./scripts/request"
import tool from './scripts/tool'
import bus from "./scripts/bus.js";
import store from "./scripts/store.js";
import _import from "./config/import_plugin"
import key from 'keymaster'
import { PluginService } from './scripts/pluginService'
import {
	format
} from 'sql-formatter';

import {
	default as $i,
	add as i18nAdd
} from "./scripts/i18n.js";
import {
	ElMessage, ElMessageBox
}
	from "element-plus";
window.Vue = Vue

const app = Vue.createApp(App)
const pluginService = new PluginService(store, config)
//挂载全局对象
app.config.globalProperties.$CONFIG = config;
app.config.globalProperties.$TOOL = tool;
app.config.globalProperties.$HTTP = http;
app.config.globalProperties.$API = api;
app.config.globalProperties.$bus = bus;
app.config.globalProperties.$pluginService = pluginService;
app.provide('$config', config)
app.provide('$bus', bus)
app.provide('$api', api)
app.provide('$message', ElMessage)
app.provide('$messageBox', ElMessageBox)
app.provide('$request', http)
app.provide('$sqlFormat', format)
app.provide("$keymaster", key);
app.provide("$pluginService",pluginService)

//加载后台插件
const getPugins = function () {
	return new Promise((resolve) => {

		let res = api.plugin.getPlugins.get({});
		const mode = import.meta.env.MODE

		res.then(res => {
			let plugins = res.data;
			Promise.all((plugins || [])
				.filter((it) => ((mode === 'production' && it.javascriptFilename) || true)).map(
					(plugin) =>
						new Promise((r) => {
							_import(plugin, {
								i18n: {
									add: i18nAdd,
									format: $i
								},
								request: http,
								config: config,
								message: ElMessage,
								messageBox: ElMessageBox,
								bus: bus,
								store: store,
								app: app
							})
								.then((pluginJs) => {
									console.log(pluginJs)
									pluginService.addPlugin(plugin.id, pluginJs);
									if (pluginJs.router) {
										//路由信息存放到缓存中
										for (let item of pluginJs.router) {
											config.STATIC_ROUTERS.push(item);
										}
									}

									r();
								})
								.catch((e) => {
									console.error(e)
									r();
								});

						})
				)).then(() => resolve())
		})

	})
}
getPugins().then(r => {
	//加载完毕后进行挂载
	app.use(Router).use(Store).use(Dbant).use(i18n).mount('#app');

});
